
import getLastEvent from '../utils/getLastEvent'
import getLastSelector from '../utils/getLastSelector'
import tracker from '../utils/tracker';


export function injectJsError () {
  //windows增加监听error事件
  window.addEventListener('error', function (event) {//错误事件对象
    console.log(event);
    let lastEvent = getLastEvent() 
    tracker.send({
      kind: 'stability',//分类
      type: 'error',//
      errorType: 'jsError',//错误类型
      url: '',//出错地址
      message: event.message,//报错信息
      filename: event.filename,
      position: `${event.lineno}:${event.colno}`,
      stack: getLines(event.error.stack),
      selector: lastEvent ? getLastSelector(lastEvent.path):''//最后一个操作元素
    })
  },true)

  //promise的error事件
  window.addEventListener('unhandledrejection', (event) => {
    let lastEvent = getLastEvent() 
    let reason = event.reason
    let message,filename,line,column,stack
    if (typeof reason === 'string') {//说明是reject的交互事件
        message = reason
    } else if (typeof reason === 'object') {//说明是一个错误对象
      if (reason.stack) {
        let matchResult = reason.stack.match(/at\s+(.+):(\d+):(\d+)/)
        filename = matchResult[1]
        line = matchResult[2]
        column = matchResult[3]
      }
      stack = getLines(reason.stack)
      message = reason.message
    }
    tracker.send({
      kind: 'stability',//分类
      type: 'error',//
      errorType: 'promiseError',//错误类型
      url: '',//出错地址
      position: line?`${line}:${column}`:undefined,
      selector: lastEvent ? getLastSelector(lastEvent.path):'',//最后一个操作元素
      message,//报错信息
      filename,
      stack,
    })
  })
}

function getLines (str) {
  return str.split('\n').slice(1).map(el=>el.replace(/^\s+at\s+/g,'')).join('^')
}

